package sk.vrto.web.presenters;

import sk.vrto.domain.Contact;
import sk.vrto.service.dao.ContactRepository;
import sk.vrto.web.base.Presenter;
import sk.vrto.web.events.ContactRemovedEvent;
import sk.vrto.web.events.ContactUpdatedEvent;
import sk.vrto.web.events.UiEmailEvent;
import sk.vrto.web.views.ContactView;

public class ContactPresenter extends Presenter<ContactView> {

    private final ContactRepository contactRepository;

    /**
     * @param contactRepository Repository for accessing contacts
     */
    public ContactPresenter(ContactRepository contactRepository) {
        this.contactRepository = contactRepository;
    }

    public void removeContact(Contact contact) {
        String email = contact.getEmail();
        contactRepository.delete(contact);
        eventBus.post(new ContactRemovedEvent(email));
    }

    /**
     * When view is in edit mode, it updates the contact in the repository
     * and propagates changes for intersted components.<br />
     * When contact is not in edit mode, edit mode is enabled.
     * @param contact Updated contact.
     */
    public void editContact(Contact contact) {
        if (view.getViewPopup().isEditMode()) {
            contact.setName(view.getViewPopup().getNameField().getValue().toString());
            contactRepository.update(contact);
            view.getViewPopup().disableEditMode();
            eventBus.post(new ContactUpdatedEvent(contact, this));
        } else {
            view.getViewPopup().enableEditMode();
        }
    }

    /**
     * Propagates event for opening new email window.
     * @param contact Contact to write new email to
     */
    public void newEmail(Contact contact) {
        eventBus.post(new UiEmailEvent.OpenWindowEvent(contact));
    }

}
